<template>
  <div class="menu" :class="{ 'menu-expanded': giveLessons }" ref="menu">
    <update-course v-if="showUpdata" :updateResource="updateResource" @closeUpdateDialog="closeUpdateDialog"> </update-course>
    <delete-mask v-if="deleteMask"></delete-mask>
    <div class="grade">
        <div class="grade-name s-20">
            {{ menuList.bookName }}
            <img v-if="menuList.bookName !== '我的课程'" @click="deleteAllBook" style="width: 24px;height: 24px;margin-left: 5px;cursor: pointer;" src="../../assets/img/home/deleteBook.png" alt="">
        </div>
        <div class="cw-tools">
            <span class="cw-t-items pointer" @click.prevent="changePublisher">
                <!-- <img src="../../assets/img/home/replace.png" alt=""> -->
                <span class="t-color-p s-14 pointer">更换教材</span>
            </span>
            <span class="separator"></span>
            <span class="cw-t-items animation-container">
                <div class="animation s-16" ref="allBookAnimation">
                    <img src="../../assets/img/home/download-tips.png" alt="" class="animation-img" />
                </div>
                <div class="animation s-16" ref="resetLesson">
                    <img src="../../assets/img/home/download-tips.png" alt="" class="animation-img" />
                </div>
                <span class="t-color-p s-14 pointer" v-if="menuList.bookName !== '我的课程'" @click="handledownloadAllBook">下载全书</span>
                <!-- <span class="separator"></span> -->
                <span class="t-color-p s-14 pointer" v-if="menuList.bookName == '我的课程'" @click="createNewLesson">课程管理</span>
                <span v-if="isUpdate" class="separator"></span>
                <span class="t-color-p s-14 pointer" v-if="isUpdate" @click="checkResUpdata">资源更新</span>
            </span>
        </div>
    </div>
    <div class="menu-content">
        <el-menu :default-active="menuList.currentLesson" class="el-menu-vertical-demo" @select="handleSelect">
            <el-submenu v-for="(item, index) in menuList.course" :key="item.id" :index="item.id">
                <template slot="title">
                    <el-tooltip :disabled="!showTollTip" class="item" effect="dark" :content="item.name" placement="top">
                      <span @mouseleave="mouseleave" @mouseenter="mouseenter" :id="'title' + index" style="font-weight: bold;width:100%;padding-left: 35px;" class="s-18 pointer">{{ item.name }}</span>
                    </el-tooltip>
                </template>
                <el-menu-item @mouseleave.self="mouseleave" v-for="(citem, cindex) in item.lessonVOList" :key="citem.id" :index="citem.id" :id="citem.id" :ref="`menuItem${citem.id}`">
                    <el-tooltip :disabled="!showTollTip" class="item" effect="dark" :content="citem.name" placement="top">
                      <div class="lesson">
                        <span :class="['s-16']" @mouseenter.self="mouseenter">
                          {{ (eduLevel === 'primary' ? cindex + 1 + '. ' : '') + citem.name }}
                        </span>
                        <div class="vip flex-center">
                          <img v-if="citem.isCharged == '0' && menuList.isAuthorized" src="../../assets/img/home/vip.png" alt="" />
                          <img v-if="citem.isCharged == '0' && !menuList.isAuthorized" src="../../assets/img/home/notvip.png" alt="" />
                        </div>
                      </div>
                    </el-tooltip>
                </el-menu-item>
          </el-submenu>
        </el-menu>
    </div>
    <div v-if=" menuList.bookName == '我的课程' && menuList.course.length == 0" class="createLesson">
        <div class="createBtn" @click="createNewLesson">创建课程</div>
        <div style="margin: 0px auto;"><span style="color: #909399;"> 如何创建课程目录? </span><span style="color: #0085FF;cursor: pointer;" @click="lookCreatCatalog">点击查看 ></span></div>
    </div>
    <div v-if="showCreateLesson">
      <create-lesson  :visible.sync="showCreateLesson"></create-lesson>
    </div>
    <div v-if="visible">
      <change-book  :bookId="menuList.bookId" :visible.sync="visible"></change-book>
    </div>
    <div class="s-16 lessons-nav" @click="toggleExpanded" v-if="giveLessons">
      <img class="menu-icon" src="../../assets/img/home/meu-icon.png" alt="" />
      目录
    </div>
  </div>
</template>

<script>
import { SqlLibUser } from '../../../../../static/lib/sqlite/service/SqlLibUser'
import { SqlLib } from '../../../../../static/lib/sqlite/SqlLib'
import resource from '../../api/resource'
import schoolApi from '../../api/school'
import { UserResource } from '../../../../../static/lib/sqlite/model/UserResource'
import { DownloadCenter } from '../../../../../static/lib/downloader/DownloadCenter'
import { SqlLibBook } from '../../../../../static/lib/sqlite/service/SqlLibBook'
import { Lesson } from '../../../../../static/lib/sqlite/model/Lesson'
import { Chapter } from '../../../../../static/lib/sqlite/model/Chapter'
import { Downloader } from '../../../../../static/lib/sqlite/model/Downloader'
import { UUIDUtil } from "../../../../../static/utils/UUIDUtil";
import usermeta from '@/content/api/usermeta'
import bus from '../../assets/js/bus.js'
import changeBook from './home_dialog/changetextbook'
import createLesson from './home_dialog/createUserLesson'
import updateCourse from './home_dialog/UpdateCourse'
import deleteMask from './home_dialog/deleteMask'
import { mapState , mapMutations} from 'vuex'

import store from '../../store/index'

export default {
  props: ['menuList', 'teachStatus', 'isInitPage'],
  inject: ['changeDownloadStatus', 'resetLesson', 'resetInitPage','initLessonItems','saveAllbook','initPage'],
  components: { changeBook, updateCourse , deleteMask  , createLesson },
  data() {
    return {
        visible: false,
        time: '',
        isSowResetDownload: false,
        isUpdate: false,
        updateResource: [],
        allBookTimeout: null,
        showTollTip: false,
        eduLevel: window.eduLevel,
        deleteMask:false,
        showCreateLesson:false,
        showUpdata:false,
    }
  },
  watch: {
    'menuList.currentLesson'(newval) {
        if (this.menuList.bookName == '我的课程') {
            this.getDiyLessonItems(newval)
        }else{
            this.getLessonItems(newval)
        } 
    },
    updateResource(val){
        console.log(' change updateResource----------------------------------------------',this.menuList.course , val);
        if (val.length == 0) {
            this.isUpdate = false
        }
    },
  },
  mounted() {
    bus.$on('initLesson', async (id,isCompleteEdit, call) => {
      await this.getLessonItems(id,isCompleteEdit)
      call && call()
    })
    bus.$on('initDiyLesson', (lessonId) => this.getDiyLessonItems(lessonId))
    bus.$on('updateLessonList', () => {
        if (this.menuList.bookName == '我的课程') {
            console.log('我的课程');
            this.getDiyLessonItems(this._lessonId)
        }else{
            this.getLessonItems(this._lessonId)
        }
    })
    bus.$on('resetDownload', () => this.resetDownload())
    bus.$on('colseCreateLesson', (isUpdate) => {
        this.showCreateLesson = false
        console.log(isUpdate);
        if (isUpdate) {
            this.initPage(this.menuList.bookId,this._lessonId,'notcheckDB')
        }
    })
    // bus.$on('isOutLesson', ()=>{
    //     let _this = this
    //     if (_this.updateResource.length == 0 ) {
    //         let sqlLib = SqlLib.getInstance(window.$DBDIR)
    //         const params = {
    //             bookId: _this.menuList.bookId,
    //         }
    //         schoolApi.getChapterLessonByBookId(params).then((response) => {
    //             if (response.code == '0') {
    //                 let temp = response.returnValue
    //                     temp.forEach((chapter) => {
    //                     let tempC = new Chapter()
    //                     tempC.id = chapter.id + ''
    //                     let lessons = chapter.lessonVOList
    //                     lessons.forEach((lesson) => {
    //                         let tempL = new Lesson()
    //                         tempL.id = lesson.id + ''
    //                         tempL.name = lesson.name
    //                         tempL.thumb = lesson.thumb
    //                         tempL.brief = lesson.brief
    //                         tempL.resVersion = lesson.resVersion
    //                         tempL.chapterId = tempC.id
    //                         tempL.isCharged = lesson.isCharged
    //                         tempL.sortIndex = lesson.sortIindex
    //                         let result = sqlLib.selectObjectById(tempL)
    //                         if (result == null) {
    //                           //如果为空，代表没查到
    //                         } else {
    //                         //查到的话，需要判断是否更新
    //                         if (result.resVersion !== lesson.resVersion) {
    //                             console.log('有需要更新的--------------',result);
    //                             _this.updateResource.push({
    //                                 src:'',
    //                                 title: tempL.name,
    //                                 id: tempL.id
    //                             })
    //                             tempL.resVersion = result.resVersion
    //                             }
    //                         }
    //                     })
    //                   })
    //                 if (_this.updateResource.length > 0) {
    //                     _this.isUpdate = true
    //                     _this.plumpUpdateDialog()
    //                 }else{
    //                     console.log('不需要更新的--------------');
    //                     _this.isUpdate = false
    //                 }
    //             }
    //         })
    //     }
    // })
    
    
  },
  activated(){
    // if (store.state.becomeVip !== 2) {
    //   this.menuList.isAuthorized =true
    // }
  },
  beforeDestroy() {
    this._lessonId = ''
  },
  computed: {
    ...mapState(['giveLessons']),
    ...mapState({
         loadingLessonSet: state => state.loadingLessonSet,
     })
  },
  methods: {
    ...mapMutations(['clearDownLoadCenter']),
    lookCreatCatalog(){
        var creatCatalogUrl = 'https://open.beautyofscience.cn/jy/index.html#/playvideo?fileId=1620360655531999232'
        const shell = require('electron').shell;
        shell.openExternal(creatCatalogUrl)
    },
    //创建新课程
    deleteAllBook(){
      if (this.loadingLessonSet.length > 0) {
        console.log(this.loadingLessonSet);
        this.$message({
            type:'warning',
            message:'课程资源下载中，请稍后重试',
            duration:3000
        })
        console.log('下载中');
        return
      }
      // localStorage.removeItem('downloadedFile')
      // localStorage.removeItem('resCoursewaresVOList')
      // localStorage.removeItem('resourceVOList')
      // localStorage.removeItem('tResPaperFileVOList')
      console.log(localStorage);
      if (localStorage.downloadedFile) {
        console.log(JSON.parse(localStorage.downloadedFile));
      }
      let rescDir = window.$DATADIR + '/resc';
      this.$showDeleteDialog(rescDir,this.menuList)
      console.log(store);
    },
    mouseenter(e) {
      let targetDom = e.target
      if (targetDom.clientWidth < targetDom.scrollWidth) {
        this.showTollTip = true
      } else {
        this.showTollTip = false
      }
    },
    mouseleave() {
       this.showTollTip = false
    },
    showForMouseenter() {
        clearTimeout(this.time)
    },
    closeForMouseout() {
        let contextmenu = this.$refs.contextmenu
        contextmenu.style.display = 'none'
    },
    resetDownload() {
      let _this = this
      let downloadingIds = DownloadCenter.getInstance().getCurrentDownloadingLesson()
      if (downloadingIds.length + 1 > this.$CONST.global.maxDownloadLesson) {
        //超出最大限制之后，不允许下载
        this.$message.warning('同时下载的课程数超过限制，请稍后重试！')
        return
      }
      if (this.resetLesson()) {
        this.$refs.resetLesson.style.animation = 'animation 2s ease  forwards'
        this.$refs.resetLesson.addEventListener('animationend', function() {
          console.log('resetDownload addEventListener animationend')
          this.style.animation = ''
          // _this.changeDownloadSum(DownloadCenter.getInstance().setDownloaders.length);
        })
      }
    },
    checkResUpdata(){
        let _this = this
        // let sqlLib = SqlLib.getInstance(window.$DBDIR)
        // if (_this.updateResource == 0) {
        //     // this.isUpdate = false
        //     // return
        //     const params = {
        //         bookId: _this.menuList.bookId,
        //     }
        //     schoolApi.getChapterLessonByBookId(params).then((response) => {
        //         if (response.code == '0') {
        //             let temp = response.returnValue
        //             //   let tempCs = []
        //             //   let tempLs = []
        //               temp.forEach((chapter) => {
        //                 let tempC = new Chapter()
        //                 tempC.id = chapter.id + ''
        //                 tempC.name = chapter.name + ''
        //                 // tempC.thumb = chapter.thumb + "";
        //                 tempC.brief = chapter.brief + ''
        //                 tempC.bookId = _this.menuList.bookId
        //                 tempC.sortIndex = chapter.sortIndex
        //                 let lessons = chapter.lessonVOList
        //                 let tempLessonVO = []
        //                 lessons.forEach((lesson) => {
        //                   let tempL = new Lesson()
        //                   tempL.id = lesson.id + ''
        //                   tempL.name = lesson.name
        //                   tempL.thumb = lesson.thumb
        //                   tempL.brief = lesson.brief
        //                   tempL.resVersion = lesson.resVersion
        //                   tempL.chapterId = tempC.id
        //                   tempL.isCharged = lesson.isCharged
        //                   tempL.sortIndex = lesson.sortIindex
        //                   let isUpdate = false //默认不需要更新
        //                   let result = sqlLib.selectObjectById(tempL)
        //                   if (result == null) {
        //                     //如果为空，代表没查到
        //                   } else {
        //                     //查到的话，需要判断是否更新
        //                     if (result.resVersion !== lesson.resVersion) {
        //                         console.log('有需要更新的');
        //                         isUpdate = true
        //                         _this.updateResource.push({
        //                             src:'',
        //                             title: tempL.name,
        //                             id: tempL.id
        //                         })
        //                         tempL.resVersion = result.resVersion
        //                     }
        //                   }
                         
        //                 })
        //               })
        //         }
        //     })
        // }
        console.log('_this.updateResource----------------------',_this.updateResource);
        this.showUpdata = true 
    },
    async getDiyLessonItems(lessonId){
        let _this = this
        let sqlLib = SqlLib.getInstance(window.$DBDIR)
        let user = SqlLibUser.queryCurrentUser(sqlLib)
        var currentItems = []
        console.log('menuList' , this.menuList);
        let lessonResource = SqlLibUser.queryLessonResource(sqlLib, user.id, _this.menuList.currentLesson)
        // console.log(lessonResource);
        if (lessonResource instanceof Array) {
            let lessonInfo = {
                lessonItems: [],
                lessonName: '',
                isRequireUpdate: false,
                isResourceEmpty: false,
                homeDialog: false,
                isCharged: '1',
                shadeInfo: {
                    authCode: '1', // 1 - 鉴权页面； 2 - 获取授权码页面
                    isDownloading: false,
                    downloadStatus: false //下载按钮的状态标识
                }
            }
            if (_this.menuList.course) {
                _this.menuList.course.forEach(item=>{
                    item.lessonVOList.forEach(val=>{
                        if (val.id == _this.menuList.currentLesson) {
                            lessonInfo.lessonName = val.name
                        }
                    })
                })
            }
            if (lessonResource.length > 0) {
                lessonResource.forEach(async resource=>{
                    if (['courseware',
                        _this.$CONST.global.selfPpt, 
                        _this.$CONST.global.selfVideo, 
                        _this.$CONST.global.selfPdf,
                        _this.$CONST.global.selfWord,
                        _this.$CONST.global.selfImg,
                        _this.$CONST.global.selfAudio,
                        'PaperFile'].includes(resource.resourceType)) {
                        let curItem = JSON.parse(resource.resourceDescription)
                        curItem.isDefault = resource.isDefault
                        curItem.downloadStatus = resource.downloadStatus
                        currentItems.push(curItem)
                    }else{//系统资源
                        let bsr = resource.resourceDescription
                        bsr = JSON.parse(bsr)
                        currentItems.push({
                            id: resource.resourceId,
                            name: bsr.meta_info.name,
                            resType: (resource.resourceClassify === '1' ? '云端资源 | ' : '课时资源 | ') + _this.$CONST.global.resourceType[resource.resourceType] + (bsr.enumType ? ' - ' + bsr.enumType : ''),
                            thumb: bsr.meta_info.thumb, //TODO
                            downloadStatus: resource.downloadStatus,
                            intro: bsr.meta_info.intro,
                            isDefault: resource.isDefault,
                            downloadInfo: {
                                TaskId: resource.resourceId,
                                FileType: resource.resourceType,
                                FileName: resource.resourceType === 'PolyvVideo' ? resource.resourceId : resource.resourceId + '.zip',
                                Url: bsr.meta_info.zip_url ? _this.$CONST.global.cdnResourcePrefix + bsr.meta_info.zip_url : '',
                                Bsr: resource.resourceDescription,
                                isLessonRes: resource.resourceClassify
                            }
                        })
                    }
                })
                lessonInfo.lessonItems = currentItems
                lessonInfo.shadeInfo.downloadStatus = false
                resource.queryDiyLessonFile({
                    lessonId:_this.menuList.currentLesson
                }).then(res=>{
                    if (res.code == '0'){
                        res.returnValue.userFileVOS.forEach((item)=>{
                            let fileType = ''
                            var resType = ''
                            switch (item.fileType) {
                                case '1':
                                    fileType = 'selfPpt'
                                    resType = 'PPT'
                                    break;
                                case '2':
                                    fileType = 'selfPdf'
                                    resType = '文档'
                                    break;
                                case '3':
                                    fileType = 'selfWord'
                                    resType = '文档'
                                    break;
                                case '4':
                                    fileType = 'selfImg'
                                    resType = '图片'
                                    break;
                                case '5':
                                    fileType = 'selfVideo'
                                    resType = '视频'
                                    break;
                                case '6':
                                    fileType = 'selfAudio'  
                                    resType = '音频'
                                    break;
                                default:
                                    break;
                            }
                            let tampName = _this.menuList.currentLesson + '-'  + item.displayName
                            let extraResource = SqlLibBook.queryOneResourceByName(sqlLib, user.id,_this.menuList.currentLesson,tampName)
                            console.log(tampName,'tampName----------------',extraResource);
                            if (!extraResource) {
                                console.log('新加了资源');
                                let userResource = new UserResource()
                                let resourceId = UUIDUtil.uuid()
                                currentItems.push({
                                    id: resourceId,
                                    name: item.displayName,
                                    resType: resType,
                                    downloadStatus: '2',
                                    isDefault: '0',
                                    downloadInfo: {
                                        TaskId: resourceId,
                                        FileType: fileType,
                                        FileName: _this.menuList.currentLesson + '-' + item.displayName,
                                        Url:item.downloadUrl,
                                    }
                                })
                                let obj = {
                                    id: resourceId,
                                    userId: user.id,
                                    lessonId: _this.menuList.currentLesson,
                                    resourceClassify: '0',
                                    resourceType: fileType,
                                    resourceId: resourceId,
                                    resourceName: _this.menuList.currentLesson + '-' + item.displayName,
                                    downloadStatus:'2',
                                    resourceDescription: JSON.stringify({
                                        id: resourceId,
                                        name: item.displayName,
                                        resType: resType,
                                        thumb: '',
                                        downloadInfo: {
                                            FileName: _this.menuList.currentLesson + '-' + item.displayName,
                                            FileType: fileType,
                                            TaskId: resourceId,
                                            Url:item.downloadUrl,
                                        },
                                        fileMd5: item.fileMd5
                                    }),
                                    reverse2 : item.fileId, //上传过后云端的唯一资源Id
                                    reverse3 : '0',
                                    isDefault: '0',
                                }
                                userResource = Object.assign(userResource, obj)
                                SqlLibBook.updateOrInsertExtraResource(sqlLib, userResource) 
                            }else{
                                console.log('已有资源');
                            }

                        })
                        let sysResource = res.returnValue.resourceIdsVO.resources
                        if (sysResource) {
                            for( let item in sysResource){
                                let searchRes = SqlLibBook.queryOneResource(sqlLib, user.id, _this.menuList.currentLesson,item)
                                if (!searchRes) {
                                    let userResource = new UserResource()
                                    let resourceId = UUIDUtil.uuid()
                                    let obj = {
                                        id: resourceId,
                                        userId: user.id,
                                        lessonId: _this.menuList.currentLesson,
                                        resourceClassify: '1',
                                        resourceType: sysResource[item].meta_info.meta_type,
                                        resourceId: item,
                                        resourceName: sysResource[item].meta_info.name,
                                        downloadStatus:searchRes ? searchRes.downloadStatus : '2',
                                        resourceDescription: JSON.stringify(sysResource[item]),
                                        isDefault: '0',
                                    }
                                    userResource = Object.assign(userResource, obj)
                                    SqlLibBook.updateOrInsertExtraResource(sqlLib, userResource) 
                                    console.log('插入的系统资源',item,sysResource[item]);
                                    currentItems.push({
                                        id: sysResource[item].id,
                                        name: sysResource[item].meta_info.name,
                                        resType: _this.$CONST.global.resourceType[sysResource[item].meta_info.meta_type],
                                        thumb: sysResource[item].meta_info.thumb, //TODO
                                        downloadStatus: '2',
                                        intro: sysResource[item].meta_info.intro,
                                        downloadInfo: {
                                            TaskId: sysResource[item].meta_info.id,
                                            FileType: sysResource[item].meta_info.meta_type,
                                            FileName: sysResource[item].meta_info.meta_type === 'PolyvVideo' ? sysResource[item].meta_info.id : sysResource[item].meta_info.id + '.zip',
                                            Url: sysResource[item].meta_info.zip_url ? _this.$CONST.global.cdnResourcePrefix + bsr.meta_info.zip : '',
                                            Bsr: JSON.stringify(sysResource[item].meta_info),
                                            isLessonRes: '1'
                                        }
                                    })
                                } 
                            }
                        } 
                    }
                })
                console.log('lessonInfo-------------------',lessonInfo);
                _this.$emit('initDiyLessonItems', lessonInfo)
            }else{
                if (localStorage.isOffline && localStorage.isOffline == 'false') {//在线
                    resource.queryDiyLessonFile({
                        lessonId:_this.menuList.currentLesson
                    }).then(res=>{
                        if (res.code == '0'){
                            res.returnValue.userFileVOS.forEach((item)=>{
                                let fileType = ''
                                var resType = ''
                                switch (item.fileType) {
                                    case '1':
                                        fileType = 'selfPpt'
                                        resType = 'PPT'
                                        break;
                                    case '2':
                                        fileType = 'selfPdf'
                                        resType = '文档'
                                        break;
                                    case '3':
                                        fileType = 'selfWord'
                                        resType = '文档'
                                        break;
                                    case '4':
                                        fileType = 'selfImg'
                                        resType = '图片'
                                        break;
                                    case '5':
                                        fileType = 'selfVideo'
                                        resType = '视频'
                                        break;
                                    case '6':
                                        fileType = 'selfAudio'  
                                        resType = '音频'
                                        break;
                                    default:
                                        break;
                                }
                                let userResource = new UserResource()
                                let resourceId = UUIDUtil.uuid()
                                currentItems.push({
                                    id: resourceId,
                                    name: item.displayName,
                                    resType: resType,
                                    downloadStatus: '2',
                                    isDefault: '0',
                                    downloadInfo: {
                                        TaskId: resourceId,
                                        FileType: fileType,
                                        FileName: _this.menuList.currentLesson + '-' + item.displayName,
                                        Url:item.downloadUrl,
                                    }
                                })
                                let obj = {
                                    id: resourceId,
                                    userId: user.id,
                                    lessonId: _this.menuList.currentLesson,
                                    resourceClassify: '0',
                                    resourceType: fileType,
                                    resourceId: resourceId,
                                    resourceName: _this.menuList.currentLesson + '-' + item.displayName,
                                    downloadStatus:'2',
                                    resourceDescription: JSON.stringify({
                                        id: resourceId,
                                        name: item.displayName,
                                        resType: resType,
                                        thumb: '',
                                        downloadInfo: {
                                            FileName: _this.menuList.currentLesson + '-' + item.displayName,
                                            FileType: fileType,
                                            TaskId: resourceId,
                                            Url:item.downloadUrl,
                                        },
                                        fileMd5: item.fileMd5
                                    }),
                                    reverse2 : item.fileId, //上传过后云端的唯一资源Id
                                    reverse3 : '0',
                                    isDefault: '0',
                                }
                                userResource = Object.assign(userResource, obj)
                                SqlLibBook.updateOrInsertExtraResource(sqlLib, userResource) 
                            })
                            //系统云资源库资源
                            let sysResource = res.returnValue.resourceIdsVO.resources
                            if (sysResource) {
                                for( let item in sysResource){
                                    let searchRes = SqlLibBook.queryOneResource(sqlLib, user.id, _this.menuList.currentLesson,item)
                                    if (searchRes) {
                                        console.log('数据库里有这个系统资源');
                                    }
                                    let userResource = new UserResource()
                                    let resourceId = UUIDUtil.uuid()
                                    let obj = {
                                        id: resourceId,
                                        userId: user.id,
                                        lessonId: _this.menuList.currentLesson,
                                        resourceClassify: '1',
                                        resourceType: sysResource[item].meta_info.meta_type,
                                        resourceId: item,
                                        resourceName: sysResource[item].meta_info.name,
                                        downloadStatus:searchRes ? searchRes.downloadStatus : '2',
                                        resourceDescription: JSON.stringify(sysResource[item]),
                                        isDefault: '0',
                                    }
                                    userResource = Object.assign(userResource, obj)
                                    SqlLibBook.updateOrInsertExtraResource(sqlLib, userResource) 
                                    console.log('插入的系统资源',item,sysResource[item]);
                                    currentItems.push({
                                        id: sysResource[item].id,
                                        name: sysResource[item].meta_info.name,
                                        resType: _this.$CONST.global.resourceType[sysResource[item].meta_info.meta_type],
                                        thumb: sysResource[item].meta_info.thumb, //TODO
                                        downloadStatus: '2',
                                        intro: sysResource[item].meta_info.intro,
                                        downloadInfo: {
                                            TaskId: sysResource[item].meta_info.id,
                                            FileType: sysResource[item].meta_info.meta_type,
                                            FileName: sysResource[item].meta_info.meta_type === 'PolyvVideo' ? sysResource[item].meta_info.id : sysResource[item].meta_info.id + '.zip',
                                            Url: sysResource[item].meta_info.zip_url ? _this.$CONST.global.cdnResourcePrefix + bsr.meta_info.zip : '',
                                            Bsr: JSON.stringify(sysResource[item].meta_info),
                                            isLessonRes: '1'
                                        }
                                    })
                                }
                            } 
                            if (currentItems.length == 0) {
                                lessonInfo.isResourceEmpty = true
                            }else{
                                console.log('有资源，不是空页面');
                                lessonInfo.isResourceEmpty = false
                            }
                        }
                    })
                    
                    lessonInfo.lessonItems = currentItems
                    lessonInfo.shadeInfo.downloadStatus = false
                    _this.$emit('initDiyLessonItems', lessonInfo)
                }else{
                    lessonInfo.isResourceEmpty = true
                    _this.$emit('initDiyLessonItems', lessonInfo)
                }
            } 
        }  
    },
    async getLessonItems(lessonId,isCompleteEdit) {
       
        let tempL = new Lesson()
        tempL.id = lessonId
        let currentLesson = SqlLib.getInstance(window.$DBDIR).selectObjectById(tempL)
        if (currentLesson.reverse3 == 'userDiy') {
            this.getDiyLessonItems(lessonId)
            return
        }
        //初始化lessonMsg
        let _this = this
        var unitId = ''
        var unitName = ''
        var lessonName = ''
        _this.menuList.course.forEach(item=>{
            item.lessonVOList.forEach(val=>{
                if (val.id == lessonId) {
                    unitId = item.id
                    unitName = item.name
                    lessonName = val.name
                }
            })
        })
        let sqlLib = SqlLib.getInstance(window.$DBDIR)
        let publishId = SqlLibBook.queryPublisherIdBybookId(sqlLib, _this.menuList.bookId)
        bus.$emit('pickLessonMsg',{
            publishId:publishId,
            bookId:_this.menuList.bookId,
            bookName:_this.menuList.bookName,
            unitId:unitId,
            unitName:unitName,
            lessonId:lessonId,
            lessonName:lessonName,
        })
        //初始化lessonMsg

        this._lessonId = lessonId
        if (lessonId) {
        let sqlLib = SqlLib.getInstance(window.$DBDIR)
        let user = SqlLibUser.queryCurrentUser(sqlLib)
        if (this.menuList.isAuthorized) {
          //如果没授权这本书，不保存课程id
          user.lessonId = lessonId
          sqlLib.updateOrInsertObjectById(user)
        }
        let lessonResource = SqlLibUser.queryLessonResource(sqlLib, this.menuList.userId, lessonId)
        if (lessonResource instanceof Array) {
          //表示查询成功
          let lessonInfo = {
            lessonItems: [],
            lessonName: '',
            isRequireUpdate: false,
            isResourceEmpty: false,
            homeDialog: false,
            isCharged: '',
            shadeInfo: {
              authCode: '1', // 1 - 鉴权页面； 2 - 获取授权码页面
              isDownloading: false,
              downloadStatus: false //下载按钮的状态标识
            }
          }
          
          _this.isSowResetDownload = false
          _this.updateResource = []
          //丰富显示状态
          this.menuList.course.forEach(course => {
            course.lessonVOList.forEach(tLesson => {
              if (tLesson.isUpdate) {
                if (course.isCharged != '0') {
                  _this.updateResource.push({
                    src: '',
                    title: tLesson.name,
                    id: tLesson.id
                  })
                } else {
                  if (this.menuList.isAuthorized) {
                    _this.updateResource.push({
                      src: '',
                      title: tLesson.name,
                      id: tLesson.id
                    })
                  }
                }
              }
              if (tLesson.id === lessonId) {
                lessonInfo.isRequireUpdate = tLesson.isUpdate
                lessonInfo.lessonName = tLesson.name
                lessonInfo.isCharged = tLesson.isCharged
                lessonInfo.shadeInfo.isDownloading = !(tLesson.isCharged == '0' && !_this.menuList.isAuthorized)
              }
            })
          })

          //丰富更新的课程列表
          if (localStorage.isOffline == 'false') {
                //在线的话，丰富更新状态
                _this.plumpUpdateDialog()
                if (_this.updateResource.length > 0 && _this.isInitPage) {
                  _this.isUpdate = true
                //   _this.resetInitPage()
                }
          }

          if (lessonResource.length > 0) {
            //表示已经下载过
            let currentItems = []
            let ppts = []
            if (localStorage.isOffline && localStorage.isOffline == 'false') {
              const res = await usermeta.getAllUserLessonFile({
                withFileUrl: '1',
                lessonId: lessonId
              })
              if (res.code == '0') {
                res.returnValue.forEach(item=>{
                    // let fileName = lessonId + '-' + item.displayName
                    // if (item.displayName == userResource.resourceName) {
                    //     // console.log('userResource',userResource);
                    //     userResource.reverse1 = item.fileId
                    //     SqlLib.getInstance(window.$DBDIR).updateOrInsertObjectById(userResource)
                    //     //用户上传ppt时本地记录的resourceId和ppt上传云端后返回的fileId不一致；用备用字段reverse1存储fileId(不影响课程列表编辑删除功能)
                    // }
                })

                // ppts = res.returnValue.map(item => item.fileMd5)
              }
            }
            const fs = require('fs')
            const getEtag = require('../../utils/qetag')
            lessonResource.forEach(async (resource, index) => {
                if (['courseware',
                    _this.$CONST.global.selfPpt, 
                    _this.$CONST.global.selfVideo, 
                    _this.$CONST.global.selfPdf,
                    _this.$CONST.global.selfWord,
                    _this.$CONST.global.selfImg,
                    _this.$CONST.global.selfAudio,
                    'PaperFile'].includes(resource.resourceType)) {
                let curItem = JSON.parse(resource.resourceDescription)
                curItem.isDefault = resource.isDefault
                curItem.downloadStatus = resource.downloadStatus
                
                if (ppts.length > 0 && curItem.downloadInfo.FileType === 'selfPpt') {
                    if (!curItem.fileMd5) {
                        const { FileName } = curItem.downloadInfo
                        const { userId } = resource
                        const filePath = window.$DATADIR + `resc/user/ppt/${userId}/${FileName}`
                        if (fs.existsSync(filePath)) {
                            const bur = fs.readFileSync(filePath)
                            const res = await getEtag(bur)
                            if (ppts.includes(res)) curItem.isUpload = true
                        }
                    } else {
                      if (ppts.includes(curItem.fileMd5)) curItem.isUpload = true
                    }
                    currentItems.push(curItem)
                }else{
                    // if (curItem.downloadInfo.FileType === 'courseware') {
                    //     const { FileName } = curItem.downloadInfo
                    //     // console.log('courseware',resource);
                    //     if (!curItem.fileMd5){
                    //         const filePath = window.$DATADIR + `resc/courseware/${FileName}`
                    //         if (fs.existsSync(filePath)) {
                    //             const bur = fs.readFileSync(filePath)
                    //             getEtag(bur).then(val => {
                    //                 curItem.fileMd5 = val
                    //                 console.log('md5',val);
                    //             })
                    //         }
                    //     }
                    //     currentItems.push(curItem)
                    // }else{
                    //     currentItems.push(curItem)
                    // }
                    currentItems.push(curItem)
                }
                } else {
                    // console.log('resource-------------------->' , resource );
                    if (resource.resourceType == undefined) {
                        this.$message.error('当前课程含有新资源类型，请您升级版本后以正常使用')
                    }
                    let bsr = resource.resourceDescription
                    bsr = JSON.parse(bsr)
                    currentItems.push({
                        id: resource.resourceId,
                        name: bsr.meta_info.name,
                        resType: (resource.resourceClassify === '1' ? '云端资源 | ' : '课时资源 | ') + _this.$CONST.global.resourceType[resource.resourceType] + (bsr.enumType ? ' - ' + bsr.enumType : ''),
                        tag: bsr.meta_info.tag === 'twig' ? 1 : 0, //0 - 美丽科学；1 - twig
                        thumb: bsr.meta_info.thumb, //TODO
                        downloadStatus: resource.downloadStatus,
                        intro: bsr.meta_info.intro,
                        isDefault: resource.isDefault,
                        downloadInfo: {
                            TaskId:  resource.resourceId,
                            FileType:resource.resourceType,
                            FileName:resource.resourceType === 'PolyvVideo' ? resource.resourceId : resource.resourceId + '.zip',
                            Url: bsr.meta_info.zip_url ? _this.$CONST.global.cdnResourcePrefix + bsr.meta_info.zip_url : '',
                            Bsr: resource.resourceDescription,
                            isLessonRes: resource.resourceClassify
                        }
                    })
                }
            })
            lessonInfo.lessonItems = currentItems
            lessonInfo.shadeInfo.downloadStatus = DownloadCenter.getInstance().lessonIsDownloading(lessonId)
            if (!lessonInfo.shadeInfo.isDownloading) {
              //代表本课时没有授权,即使下载过课时也要授权
              lessonInfo.homeDialog = true
            }
            _this.$emit('initLessonItems', lessonInfo ,isCompleteEdit)
          } else {
            //表示未下载
            if (localStorage.isOffline && localStorage.isOffline == 'false') {
              //表示在线
              let options = {
                title: '正在加载课程',
                time: 15000,
                progress: false,
                full: true
              }
              let loadingMask = _this.$downloadmask('#home', options)
              _this.getResAndCoueseware(this.menuList.userId, lessonId, function(lessonItems, itemBsr, isResourceEmpty) {
                lessonInfo.isResourceEmpty = isResourceEmpty
                if (!isResourceEmpty) {
                  lessonInfo.homeDialog = true
                  _this.isSowResetDownload = true
                  resource
                    .getResourceInfoByResIds({ metaParamDTOS: itemBsr })
                    .then(response => {
                      let bsrResources = response.returnValue.resources
                    //   console.log('bsrResources-------------------->',bsrResources);
                    //   return
                      lessonItems.forEach((item, index) => {
                        if (bsrResources[item.id]) {
                          let bsr = bsrResources[item.id]
                          bsr.brief = item.brief ? item.brief : ''
                          bsr.intro = item.intro ? item.intro : ''
                          bsr.scenarios = item.scenarios ? item.scenarios : ''
                          bsr.meta_info.name = item.name
                          if (item.downloadInfo.FileType === 'VirtualLab') {
                            console.log(bsrResources)
                            item.resType += ' - ' + bsrResources[item.id].enumType
                          }
                          item.downloadInfo.Bsr = JSON.stringify(bsr)
                        }
                        if (item.downloadInfo.FileType === 'courseware' || item.downloadInfo.FileType === 'PaperFile') {
                          item.downloadInfo.Bsr = JSON.stringify(item)
                        }
                      })
                      console.log(lessonItems);
                      lessonInfo.lessonItems = lessonItems
                      lessonInfo.shadeInfo.downloadStatus = DownloadCenter.getInstance().lessonIsDownloading(lessonId)
                      _this.$emit('initLessonItems', lessonInfo)
                      loadingMask.close()
                    })
                    .catch(error => {
                      _this.$message('网络异常，数据初始化失败！')
                      loadingMask.close()
                    })
                } else {
                  _this.$emit('initLessonItems', lessonInfo)
                  loadingMask.close()
                }
              })
            } else {
              lessonInfo.isResourceEmpty = true
              _this.$emit('initLessonItems', lessonInfo)
            }
          }
        } else {
          this.$message.warning('资源初始化失败，请重试！')
        }
      }
    },
    getResAndCoueseware(userId, lessonId, callback) {
      let _this = this
      resource
        .getResAndCouesewareByLessonId({ lessonId: lessonId })
        .then(response => {
          let result = []
          let resultBsr = []
          let resAndCouse = response.returnValue
          let isResourceEmpty = false
          if (resAndCouse.resCoursewaresVOList && resAndCouse.resCoursewaresVOList.length > 0) {
            resAndCouse.resCoursewaresVOList.forEach((course, index) => {
              let courseObj = {
                id: course.id,
                name: course.title,
                resType: 'PPT',
                tag: course.tag === 'twig' ? 1 : 0, //0 - 美丽科学；1 - twig
                thumb: course.thumb,
                downloadInfo: {
                  FileName: course.id + '.pptx',
                  FileType: 'courseware',
                  TaskId: course.id,
                  Url: course.url
                }
              }
              if (index === 0) {
                courseObj.isDefault = '1'
              } else {
                courseObj.isDefault = '0'
              }
              result.push(courseObj)
              resultBsr.push({
                metaId: course.id,
                metaType: 'courseware'
              })
            })
          }
          if (resAndCouse.resourceVOList && resAndCouse.resourceVOList.length > 0) {
            let quizes = []
            resAndCouse.resourceVOList.forEach(resource => {
              let info = {
                id: resource.resMetaInfoVO.meta_id,
                name: resource.name,
                resType: '课时资源 | ' + _this.resTypeToName(resource.resMetaInfoVO.res_type),
                tag: resource.tag === 'twig' ? 1 : 0, //0 - 美丽科学；1 - twig
                thumb: resource.resMetaInfoVO.thumb,
                brief: resource.brief ? resource.brief : '',
                intro: resource.intro ? resource.intro : '',
                scenarios: resource.scenarios ? resource.scenarios : '',
                downloadInfo: {
                  TaskId: resource.resMetaInfoVO.meta_id,
                  FileType: _this.resTypeToEnName(resource.resMetaInfoVO.res_type),
                  FileName: _this.resTypeToEnName(resource.resMetaInfoVO.res_type) === 'PolyvVideo' ? resource.resMetaInfoVO.meta_id : resource.resMetaInfoVO.meta_id + '.zip',
                  Url: resource.resMetaInfoVO.zip_url ? _this.$CONST.global.cdnResourcePrefix + resource.resMetaInfoVO.zip_url : ''
                }
              }
              resultBsr.push({
                metaId: resource.resMetaInfoVO.meta_id,
                metaType: _this.resTypeToEnName(resource.resMetaInfoVO.res_type)
              })
              if (_this.resTypeToEnName(resource.resMetaInfoVO.res_type) == 'Quiz') {
                quizes.push(info)
              } else {
                result.push(info)
              }
            })
            result = result.concat(quizes)
          }
          if (resAndCouse.tResPaperFileVOList && resAndCouse.tResPaperFileVOList.length > 0) {
            resAndCouse.tResPaperFileVOList.forEach(resource => {
              let info = {
                id: resource.id,
                name: resource.name,
                resType: '课时资源 | 文档资源',
                tag: resource.tag === 'twig' ? 1 : 0, //0 - 美丽科学；1 - twig
                thumb: resource.thumb,
                brief: resource.brief ? resource.brief : '',
                intro: resource.intro ? resource.intro : '',
                scenarios: resource.scenarios ? resource.scenarios : '',
                downloadInfo: {
                  TaskId: resource.id,
                  FileType: 'PaperFile',
                  FileName: resource.id + '.pdf',
                  Url: resource.url
                }
              }
              resultBsr.push({
                metaId: resource.id,
                metaType: 'PaperFile'
              })
              result.push(info)
            })
          }
          if (!resAndCouse.resourceVOList && !resAndCouse.resCoursewaresVOList && !resAndCouse.tResPaperFileVOList) {
            isResourceEmpty = true
          } else {
            if (
              resAndCouse.resCoursewaresVOList instanceof Array &&
              resAndCouse.resCoursewaresVOList.length === 0 &&
              resAndCouse.tResPaperFileVOList instanceof Array &&
              resAndCouse.tResPaperFileVOList.length === 0 &&
              resAndCouse.resourceVOList instanceof Array &&
              resAndCouse.resourceVOList.length === 0
            ) {
              isResourceEmpty = true
            }
          }
          if (callback) {
            callback(result, resultBsr, isResourceEmpty)
          }
        })
        .catch(error => {
          _this.$message.error('网络异常，加载资源失败！')
        })
    },
    //判断磁盘大小
    judgediskSize(){
        let _this = this
        var diskinfo = require('diskinfo'); // 需安装diskinfo依赖
        var currentDisk = process.cwd().substr(0, 2).toUpperCase()
        console.log(currentDisk);
        try {
            diskinfo.getDrives(function (err,aDrives) {
                console.log('aDrives-------------',aDrives);
            	for (var i = 0; i < aDrives.length; i++) {
                    if(aDrives[i].mounted.toUpperCase() === currentDisk){
                        // if (aDrives[i].blocks) {
                            console.log(aDrives[i]);
                            console.log('磁盘：' + aDrives[i].mounted);
            	            console.log('磁盘总内存：' + aDrives[i].blocks);
            	            console.log('磁盘已用内存：' + aDrives[i].used);
            	            console.log('磁盘可用内存：' + (aDrives[i].available/1024/1024/1024).toFixed('0') + 'gb');
            	            console.log('磁盘已用内存百分比： ' + aDrives[i].capacity);
                            localStorage.setItem('available' , (aDrives[i].available/1024/1024).toFixed('0'));
                            return
                        // }
                    }
            	}
            })
        } catch (error) {
            console.log(error);
            return 
        }  
    },
    handledownloadAllBook(){
        this.judgediskSize()
        setTimeout(() => {
            if (localStorage.getItem('available') &&  localStorage.getItem('available') < 1024) {
                this.$message.warning('请及时清理磁盘空间以满足下载')
                // return
            }
            this.downloadAllBook ()
        }, 100);
    },
    downloadAllBook() {
      if (!localStorage.isOffline || localStorage.isOffline == 'true') {
        //离线用不了
        this.$message.warning('您当前处于离线状态，不能使用下载全书功能')
        return
      }
      if (!this.menuList.isAuthorized) {
        this.$message.warning('非VIP不可以使用全书下载功能！')
        return
      }
      let _this = this
      this.$refs.allBookAnimation.removeEventListener('animationend', function() {})
      
      if (_this.allBookTimeout) {
        //首先移除之前的timeoutId
        clearTimeout(_this.allBookTimeout)
      }

      let sqlLib = SqlLib.getInstance(window.$DBDIR)

      let allLesson = SqlLibBook.queryAllLessonInfoByBookId(sqlLib, _this.menuList.bookId)
      // console.log(allLesson);
      const user = SqlLibUser.queryCurrentUser(sqlLib)
    //   const allDownloadedLesson = sqlLib.queryAllDownloadedLessonByUserId(user.id)
    //   const allDownloadedLessonIds = []
    //   allDownloadedLesson.forEach(item => {
    //     allDownloadedLessonIds.push(item.id.split('-')[0])
    //   })
      let downloadedIds = DownloadCenter.getInstance().getCurrentDownloadLesson()
      let resultLesson = []
      allLesson.forEach((lesson, index) => {
        if (!downloadedIds.includes(lesson.SetDownloadId)) {
          resultLesson.push(lesson)
        }
      })
      // let user = SqlLibUser.queryCurrentUser(sqlLib);
      let downloadingIds = DownloadCenter.getInstance().getCurrentDownloadingLesson()
      if (downloadingIds.length + resultLesson.length > _this.$CONST.global.maxDownloadLesson) {
        //超出最大限制之后，不允许下载
        _this.$message.warning('同时下载的课程数超过限制，请稍后重试！')
        return
      }
      if (resultLesson.length === 0) {
        console.log('资源个数为0')
        _this.$message.warning('全书已经加入下载中心！')
      } else {
        let currentLessonId = _this.menuList.currentLesson
        this.$refs.allBookAnimation.style.animation = 'animation 2s ease  forwards'
        this.$refs.allBookAnimation.addEventListener('animationend', function() {
          console.log('downloadAllBook addEventListener animationend')
        //   return
        //   _this.saveAllbook()
          this.style.animation = ''
          _this.changeDownloadStatus(true, currentLessonId)
          
        })
        _this.allBookTimeout = setTimeout(function() {
            //TODO 下载恢复功能： 保存课程信息，后续调整为关闭保存
            // sqlLib.updateDownloadingLesson(resultLesson, user.id, moment().format("YYYY-MM-DD HH:mm:ss"))
            console.log('downloadAllBook syncPushDownloadCenter---------------------------------------------', resultLesson)
            DownloadCenter.getInstance().syncPushDownloadCenter(resultLesson)
            resultLesson = []
            // _this.changeDownloadSum(DownloadCenter.getInstance().setDownloaders.length);
        }, 2000)
      }
          
    },
    handleSelect(key, keyPath) {
        let _this = this
        if (this.teachStatus == '下课') {
            this.$dialog({
              confirm: '确认',
              message: '您当前的课程正处于上课状态，请点击“下课”后再切换其他课程',
              close: false,
              type: 'warn'
            })
            .then(() => {
              _this.assignMenuItem(_this.menuList.currentLesson)
            })
            .catch(() => {})
        } else {
            console.log('赋值 currentLesson')
            // console.log(this.menuList);
            var unitId = ''
            this.menuList.course.forEach(item=>{
                item.lessonVOList.forEach(val=>{
                    if (val.id == key) {
                        unitId = item.id
                    }
                })
            })
            let sqlLib = SqlLib.getInstance(window.$DBDIR)
            let publishId = SqlLibBook.queryPublisherIdBybookId(sqlLib, _this.menuList.bookId)
            bus.$emit('pickLessonMsg',{
                publishId:publishId,
                bookId:this.menuList.bookId,
                unitId:unitId,
                lessonId:key,
            })
            _this.menuList.currentLesson = key
            _this.assignMenuItem(key)
            bus.$emit('isshowdownloadAgain' , false)
        }
    },
    resTypeToName(resType) {
        resType = this.$CONST.global.resourceSwitch[resType]
        return this.$CONST.global.resourceType[resType]
    },
    resTypeToEnName(resType) {
      return this.$CONST.global.resourceSwitch[resType]
    },
    plumpUpdateDialog() {
      let _this = this
      if (this.updateResource.length > 0) {
        let lessonIds = []
        let currentUpdateResource = []
        let sqlLib = SqlLib.getInstance(window.$DBDIR)
        //去除不需要更新的课时（未下载的课时）
        this.updateResource.forEach((resource, index) => {
          let lessonResource = SqlLibUser.queryLessonResource(sqlLib, this.menuList.userId, resource.id)
          if (lessonResource instanceof Array) {
            if (lessonResource.length > 0) {
              lessonIds.push(resource.id)
              currentUpdateResource.push(resource)
            }
          }
        })
        this.updateResource = currentUpdateResource
        resource
          .getLessonPicByIds({
            lessonIds: lessonIds
          })
          .then(response => {
            if (response.code == '0') {
              if (response.returnValue) {
                let lessonThumbs = response.returnValue.lessonThumbs
                if (lessonThumbs) {
                  this.updateResource.forEach(resource => {
                    resource.src = lessonThumbs[resource.id]
                  })
                }
              }
            }
          })
      }
    },
    closeUpdateDialog() {
        this.showUpdata = false
        // this.isUpdate = false
    },
    assignMenuItem(id) {
      let doms = document.getElementsByClassName('el-menu-item is-active')
      for (let i = doms.length - 1; i >= 0; i--) {
        doms[i].classList.remove('is-active')
      }
      let currentDom = document.getElementById(id)
      currentDom.classList.add('is-active')
    },
    changePublisher() {
        if (this.teachStatus == '下课') {
            this.$message.warning('您当前正处于上课状态，不能切换教材！')
        } else {
            this.visible = true
            this.deleteAll = true
        }
    },
    createNewLesson(){
        if (this.teachStatus == '下课') {
            this.$message.warning('您当前正处于上课状态，无法创建课程！')
        } else {
            console.log('创建课程');
            if (localStorage.isOffline && localStorage.isOffline == 'false') {
                this.showCreateLesson = true
            }else{
                this.$message.warning('网络未连接，无法使用')
            }
            
        }
    },
    menuOpen(index) {
      console.log(index)
    },
    toggleExpanded() {
      this.$refs.menu.classList.toggle('menu-expanded')
    }
  }
}

</script>

<style lang="scss">
// @media screen and (min-width: 1440px) {
.menu {
  width: 280px;
  // padding-right: 15px;
  padding-top: 18px;
  box-sizing: border-box;
  background: url(../../assets/img/home/home-bg.png) no-repeat;
  background-size: cover;
  background-position: 0 100%;
//   background: #F4F9FF;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  z-index: 20;
  transition: all 0.7s ease-in-out;
  &-expanded {
    transform: translateX(-101%);
  }
  .createLesson{
    width: 100%;
    position: absolute;
    top:calc(50% - 40px);
    display: flex;
    flex-direction: column;
    justify-content: center;
    .createBtn{
        width: 120px;
        height: 40px;
        background: linear-gradient(270deg, #46DDFF 0%, #0085FF 100%);
        border-radius: 4px;
        line-height: 40px;
        border: none;
        color: #fff;
        cursor: pointer;
        margin: 20px auto;
        text-align: center;
    }
  }
  .handleDeleteBook{
    width: auto;
    cursor: pointer;
    position: relative;
    top: 2px;
    left: 8px;
    display: flex;
    align-items: center;
    .deletebookText{
      width: 64px;
      // height: 15px;
      font-size: 14px;
      font-weight: 400;
      color: #909293;
      cursor: pointer;
      position: relative;
      left: 8px;
      bottom: 1px;
    }
  }
  .lessons-nav {
    position: absolute;
    right: 0;
    width: 30px;
    height: 88px;
    text-align: center;
    // background: #0085ff;
    background: linear-gradient(270deg, #46DDFF 0%, #0085FF 100%);

    top: 0;
    bottom: 0;
    right: 0;
    margin: auto 0;
    cursor: pointer;
    color: #fff;
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
    transform: translateX(100%);
    .menu-icon {
      width: 13px;
      height: 10px;
      margin-bottom: 9px;
    }
  }
  .contextmenu {
    position: absolute;
    color: #4894ff;
    background: #fff;
    padding: 10px;
    z-index: 1000;
    margin-left: 10px;
    border-radius: 8px;
    display: none;
    transition: all 1s ease;
  }
  .grade {
    padding-left: 30px;
    margin-bottom: 20px;
    .grade-name {
        font-weight: bold;
        margin-bottom: 14px;
        // padding-left: 20px;
    }
    .cw-tools {
        display: flex;
        align-items: center;
    }
    .separator {
      display: inline-block;
      width: 1px;
      height: 14px;
      background-color: rgba(209, 219, 226, 1);
      margin: 0 11px;
      margin-top: 2px;
    }
  }
  .menu-content {
    width: 100%;
    height: 78.9vh;
    overflow-y: auto;
    overflow-x: hidden;
    
  }
  .el-menu {
   
    background-color: transparent;
    border: none;
    .el-menu--inline {
        // padding-left: 30px;
        // transform: translateX(-32px);
    }
  }
  .el-submenu__icon-arrow {
    left: 0vw;
    top: 60%;
    right: 0;
    width: 20px;
  }
  .el-submenu.is-opened > .el-submenu__title .el-submenu__icon-arrow {
    transform: none;
    &::before {
      transform: rotate(90deg);
    }
  }
  .el-icon-arrow-down:before {
    font-family: element-icons !important;
    content: '\e791';
    left: 6px;
    top: 50%;
    right: 0;
    margin-left: 32px;
    display: inline-block;
  }
  .el-menu-vertical-demo {
    margin-bottom: 10px;
  }
  .el-menu-item,
  .el-submenu__title {
    
    width: 280px;
    height: 40px;
    line-height: 40px;
    font-size: 16px;
    & > span {
      text-overflow: ellipsis;
      white-space: nowrap;
      text-align: left;
      overflow: hidden;
    }
  }
  .el-submenu .el-menu-item {

    width: 280px;
    height: 40px;
    line-height: 40px;
    font-size: 14px;
    padding-right: 0;
    padding-left: 30px;
    color: #606266;
    margin: 5px 0;
  }

  .el-menu-item {
    // margin: 5px 0;
    min-width: 0;
    text-align: left;
    display: inline-block;
    color: #000;
    box-sizing: border-box;
  }
  .el-menu-item:hover {
    color: #4894ff;
  }
  .el-menu-item.is-active {
    color: #fff;
    background: linear-gradient(270deg, #46DDFF 0%, #0085FF 100%);
  }
  .lesson {
    padding-left: 16px;
    position: relative;
    width: 100%;
    & > span {
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        text-align: left;
        display: inline-block;
        width: 100%;
        margin-top: -4px;
        cursor: pointer;
    }
  }
  .update {
    position: relative;
    &::after {
      content: '';
      width: 8px;
      height: 8px;
      border-radius: 50%;
      position: absolute;
      top: 0;
      right: 0;
      transform: translate(100%, -100%);
      background-color: #f56c6b;
    }
  }
  .vip {
    position: absolute;
    height: 100%;
    line-height: 100%;
    top: 0px;
    left: -11px;
    img {
      width: 18px;
      height: 16px;
    }
  }
  .cw-t-items {
    display: flex;
    align-items: center;
    img {
      width: 18px;
      height: 18px;
    }
  }
}

// }
</style>
